package cn.hgpu.servlet;

import cn.hgpu.mapper.AdminMapper;
import cn.hgpu.pojo.Admin;
import cn.hgpu.utils.MybatisUtils;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/menu/edit")
public class MenuEditServlet extends HttpServlet {
    AdminMapper adminMapper = MybatisUtils.getMapper(AdminMapper.class);
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数
        String id = req.getParameter("id");
        String name = req.getParameter("adminName");
        String pwd = req.getParameter("pwd");

        //1.逻辑处理
        // 判断
        //1.不能为空
        if(StringUtils.isNullOrEmpty(name)||StringUtils.isNullOrEmpty(pwd)){
            req.setAttribute("msg","管理员名称或密码不能为空！");
            //转发
            req.getRequestDispatcher("/admin/edit.jsp").forward(req,resp);
            return;
        }
        //2.不能重复
        Admin admin = adminMapper.selectByAdmin(name);
        if(admin!=null&&Integer.parseInt(id)!=admin.getId()){
            req.setAttribute("msg","管理员信息不能重复！");
            //转发
            req.getRequestDispatcher("/admin/edit.jsp").forward(req,resp);
            return;
        }

        // 修改管理员信息
        adminMapper.update(Integer.parseInt(id),name,pwd);
        MybatisUtils.commit();

        //修改成功，跳转到查询servlet,经过其跳转到首页
        resp.sendRedirect("/admin/list");
    }
}

